#! /bin/sh

ERL_CRASH_DUMP=${ERL_CRASH_DUMP-"/dev/null"}

cleanup () {
  erl -pa ../src -sname herd_add_node_killah -eval '
    "herd_add_node_killah@" ++ Host = atom_to_list (node ()),
    Other = list_to_atom ("herd_add_node_test1@" ++ Host),
    MoreOther = list_to_atom ("herd_add_node_test2@" ++ Host),

    rpc:call (Other, erlang, halt, []),
    rpc:call (MoreOther, erlang, halt, [])
  ' -noshell -noinput -s erlang halt 
  wait
}

trap 'cleanup;' EXIT
trap 'exit 1;' INT HUP QUIT TERM

set -e

erl -pa ../src -sname herd_add_node_test1 \
    -eval '
  receive after infinity -> ok end' \
  -s erlang halt -noshell -noinput &

sleep 1

erl -pa ../src -sname herd_add_node_test2 \
    -eval '
  receive after infinity -> ok end' \
  -s erlang halt -noshell -noinput &

sleep 1

erl -pa ../src -sname herd_add_node_test3 -eval '
  timer:kill_after (10000),
  "herd_add_node_test3@" ++ Host = atom_to_list (node ()),
  Self = node (),
  Other = list_to_atom ("herd_add_node_test1@" ++ Host),
  MoreOther = list_to_atom ("herd_add_node_test2@" ++ Host),
  pong = net_adm:ping (Other),

  { ok, _ } = gen_herd_test:start (3, 2, 4),

  [ Self ] = [ node (P) || P <- pg2:get_members (gen_herd_test) ],

  [ [ Self ], [ Self ], [ Self ] ] = 
    [ lists:sort ([ node (P) || P <- pg2:get_members (Group) ])
      || Group <- pg2:which_groups (),
         string:substr (atom_to_list (Group), 1, 14) =:= "gen_herd_test_" ],

  { ok, OtherPid } = rpc:call (Other, gen_herd_test, start, [ 3, 2, 4 ]),

  global:sync (),
  [ Other, Self ] = [ node (P) || P <- pg2:get_members (gen_herd_test) ],

  [ [ Other, Self ], [ Other, Self ], [ Other, Self ] ] = 
    [ lists:sort ([ node (P) || P <- pg2:get_members (Group) ])
      || Group <- pg2:which_groups (),
         string:substr (atom_to_list (Group), 1, 14) =:= "gen_herd_test_" ],

  { ok, Pid } = rpc:call (MoreOther, gen_herd_test, start, [ 3, 2, 4 ]),

  global:sync (),
  [ MoreOther, Other, Self ] = [ node (P) || P <- pg2:get_members (gen_herd_test) ],

  [ [ Other, MoreOther ], [ Other, Self ], [ MoreOther, Self ] ] = 
    lists:sort (
      [ lists:sort ([ node (P) || P <- pg2:get_members (Group) ])
        || Group <- pg2:which_groups (),
           string:substr (atom_to_list (Group), 1, 14) =:= "gen_herd_test_" ]),
  ok
' -noshell -noinput -s erlang halt 2>&1 > addnode.output 

exit 0
